package com.jvtd.eyl.ui.main.bookcase;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jakewharton.rxbinding2.view.RxView;
import com.jvtd.eventBus.EventCenter;
import com.jvtd.eyl.R;
import com.jvtd.eyl.base.BaseMvpFragment;
import com.jvtd.eyl.bean.eventBus.MainBarBean;
import com.jvtd.eyl.bean.http.MyBookBean;
import com.jvtd.eyl.constants.EventCode;
import com.jvtd.eyl.databinding.FragmentBookcaseBinding;
import com.jvtd.eyl.ui.main.MainActivity;
import com.jvtd.eyl.ui.main.home.search.SearchActivity;
import com.jvtd.eyl.widget.EditorView;
import com.jvtd.utils.SmartRefreshUtils;
import com.jvtd.utils.UiUtils;
import com.jvtd.widget.emptyView.JvtdEmptyView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

/**
 * 书架
 *
 * 作者:chenlei
 * 时间:2018/11/12 4:11 PM
 */
public class BookcaseFragment extends BaseMvpFragment implements BookcaseMvpView, OnRefreshListener {
    @Inject
    BookcasePresenter<BookcaseMvpView> mPresenter;
    private FragmentBookcaseBinding mBinding;

    public static BookcaseFragment newInstance() {

        Bundle args = new Bundle();

        BookcaseFragment fragment = new BookcaseFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        MainBarBean mainBarBean = new MainBarBean(false,true);
        EventBus.getDefault().post(new EventCenter<>(mainBarBean,EventCode.UPDATE_BAR));
    }

    @Override
    public void onDestroyView() {
        mPresenter.onDetach();
        super.onDestroyView();
    }

    @Override
    protected View getLayout(LayoutInflater inflater, @Nullable ViewGroup container) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_bookcase, container, false);
        return mBinding.getRoot();
    }

    @Override
    protected void initViewAndData() {
        mPresenter.onAttach(this);

        initToolbar();

        initRefreshLayout();

        initRecyclerView();

        mBinding.editorView.setImage(R.drawable.icon_delete);
        mBinding.editorView.setOnEditorListener(new EditorView.OnEditorListener() {
            @Override
            public void onSelectAll(boolean all) {
                mBinding.recyclerView.selectAll(all);
            }

            @Override
            public void onClick(View view) {
                mPresenter.delMyBook(mBinding.recyclerView.getSelectedData());
                editor(false);
            }
        });

        editor(false);

        onRefresh(null);
    }

    private void initToolbar() {
        setToolbar(mBinding.toolBar.toolBar, false);
        UiUtils.moveStatusBarHeight(mBinding.toolBar.toolBar);
        addDisposable(RxView.clicks(mBinding.toolBar.ivSearch).throttleFirst(1, TimeUnit.SECONDS).subscribe(o -> startActivity(SearchActivity.getIntent(mContext))));
        addDisposable(RxView.clicks(mBinding.toolBar.ivClose).throttleFirst(1, TimeUnit.SECONDS).subscribe(o -> editor(false)));
        addDisposable(RxView.clicks(mBinding.toolBar.tvEditor).throttleFirst(1, TimeUnit.SECONDS).subscribe(o -> editor(true)));
    }

    private void initRefreshLayout() {
        SmartRefreshUtils.initRefresh(mContext, mBinding.refreshLayout, this);
    }

    private void initRecyclerView() {
        mBinding.recyclerView.openEmptyView((view, state) -> {
            if (state == JvtdEmptyView.STATE_ERROR)
                onRefresh(null);
        });
        mBinding.recyclerView.setRefreshLayout(mBinding.refreshLayout);
        mBinding.recyclerView.setOnSelectedChangeListener(() -> mBinding.editorView.setNum(mBinding.recyclerView.getSelectedData().size(), EditorView.SUB));
        if (mBinding.recyclerView.getAdapter() != null) {
            mBinding.recyclerView.getAdapter().setOnItemLongClickListener((adapter, view, position) -> {
//      MyBookBean myBookBean = (MyBookBean) adapter.getData().get(position);
//      new AlertDialog().setTitle(getString(R.string.prompt))
//              .setMessage(String.format(getString(R.string.is_del_book_tips),myBookBean.getDtitle(),myBookBean.getDocumentperiodical().getName()))
//              .setShowContentLayout(true)
//              .setOnClickListener((isLeft, inputText) -> {
//                if (!isLeft)
//                  mPresenter.delMyBook(Collections.singletonList(myBookBean));
//              })
//              .show(getFragmentManager());
                if (mBinding.recyclerView.isEditor()) return false;
                editor(true);
                return false;
            });
        }
    }

    private void editor(boolean editor) {
        mBinding.editorView.setNum(0, EditorView.SUB);
        mBinding.editorView.setVisibility(!editor ? View.GONE : View.VISIBLE);
//    mBinding.toolBar.tvEditor.setVisibility(editor ? View.GONE : View.VISIBLE);
        mBinding.toolBar.ivSearch.setVisibility(editor ? View.GONE : View.VISIBLE);
        mBinding.toolBar.ivClose.setVisibility(!editor ? View.GONE : View.VISIBLE);
        if (editor) {
            mBinding.toolBar.tvTitle.setText(R.string.bookcase_editor_title);
        } else {
            mBinding.toolBar.tvTitle.setText(R.string.my_bookcase_title);
        }
        mBinding.recyclerView.editor(editor);
        if (getActivity() != null) {
            MainActivity mainActivity = (MainActivity) getActivity();
            mainActivity.hideNavigation(editor);
        }
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mPresenter.getMyBookList();
    }


    @Override
    public void getMyBookListSuccess(List<MyBookBean> bookBeans) {
        mBinding.recyclerView.setData(bookBeans);
    }

    @Override
    public void getMyBookListFailed() {
        mBinding.recyclerView.firstLoadFailed();
    }

    @Override
    public void delMyBookSuccess() {
        onRefresh(null);
    }

    @Override
    public void fragmentOnEvent(EventCenter eventCenter) {
        switch (eventCenter.getEventCode()) {
            case EventCode.ADD_BOOK_SUCCESS:
                if (mPresenter != null)
                    onRefresh(null);
                break;
        }
    }
}
